package main.Tests;

import java.io.IOException;
import java.nio.file.Path;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import main.FileVisitors.MyFileVisitor;
import main.FileVisitors.FileVisitorImpl.AtomicFileVisitor;
import main.Runnable.RunCount;

public class TestConcurrency extends Test {

    public TestConcurrency(final String walkOnDrive, final int numberOfTests, final int maxThreadsPerTest, final String searchWithNoRegistry)
            throws IOException, InterruptedException {
        this.walkOnDrive = walkOnDrive;
        this.numberOfTests = numberOfTests;
        this.maxThreadsPerTest = maxThreadsPerTest;
        this.searchWithNoRegistry = searchWithNoRegistry;
        printHeader(numberOfTests);
        runInitRootDirectories(walkOnDrive);
    }

    public void runTest() throws InterruptedException, IOException {
        for (int j = 0; j < numberOfTests; j++) {
            print(String.format("----- Iteration: %d -----%n", j + 1));
            while (startActiveThreads <= maxThreadsPerTest) {
                final AtomicFileVisitor visitor = new AtomicFileVisitor(searchWithNoRegistry);

                long time = System.currentTimeMillis();
                runCount(visitor);
                time = System.currentTimeMillis() - time;

                print(resultToString(visitor, time, walkOnDrive));
                startActiveThreads++;
            }
            startActiveThreads = 1;
        }
        printFooter();
    }

    private void runCount(final MyFileVisitor visitor) throws InterruptedException {
        final ExecutorService service = Executors.newFixedThreadPool(startActiveThreads);
        for (final Path path : rootDirectories.getRootDirectories()) {
            final RunCount runCount = new RunCount(path, visitor);
            service.execute(runCount);
        }
        serviceShutdown(service);
    }
}
